<template>
  <div class="content_box">
    <!-- 视频混剪头部 start -->
    <div class="smart-clip-header">
      <div class="smart-clip-header-title_top">
        爆店码
        <a-popover overlayClassName="popover_con" placement="rightBottom">
          <template #content>
            <div>
              <div>
                视频相关数据具有延迟性，一般为T+1展示，如果获取数据为空，可能有以下几个原因：
              </div>
              <div>
                1、用户首次授权应用，需第二天才能产出该用户视频相关数据。
              </div>
              <div>
                2、第二天数据产出数据时间约为20:00前，如遇数据任务异常，可能会T+2产出。
              </div>
              <div>3、三十天内创建的视频，才会返回数据。</div>
              <div>4、若发布的视频是非公开的，则也不会拉取到数据。</div>
            </div>
          </template>
          <question-circle-outlined style="font-size: 16px" />
        </a-popover>
      </div>
      <div class="smart-clip-header-desc">
        爆店码，让每个抖音用户成为你的宣传官
        。商家将事先编辑好的视频上传到系统，再下载活动二维码。任意线下用户通过抖音扫码，系统会自动发布商家预设好的视频到用户的个人抖音账号上，并带有视频的地理位置，从而吸引更多同城用户的关注。
      </div>
      <div class="smart-clip-header-desc">
        因抖音政策调整，爆店码发布的数据量拉取正在维护中。
      </div>
    </div>

    <div class="content_card">
      <div class="top_btn">
        <a-button type="primary" class="add_btn" @click="addBurstShop"
          >添加爆店码
          <template #icon>
            <plus-outlined />
          </template>
        </a-button>
      </div>

      <div class="content_table">
        <a-table
          :scroll="{
            x:2000
          }"
          :columns="columns"
          :data-source="dataSource"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key == 'name'">
              <div class="name_content">
                <!-- <div class="left">
                  <img class="corver_img" :src="record.poster" alt="" />
                </div> -->
                <div class="right">
                  <a-popover placement="top" overlayClassName="popover_cons">
                    <template #content>
                      <div style="width: 200px">{{ record.name }}</div>
                    </template>
                    <div class="right_one">{{ record.name }}</div>
                  </a-popover>

                  <div class="right_two">{{ record.end_time }}</div>
                </div>
              </div>
            </template>
            <template v-if="column.key == 'activity_status'">
              <a-tag color="#108ee9" v-if="record.activity_status == '0'">{{
                record.activity_status_txt
              }}</a-tag>
              <a-tag
                color="#87d068"
                v-else-if="record.activity_status == '1'"
                >{{ record.activity_status_txt }}</a-tag
              >
              <a-tag color="#f50" v-else-if="record.activity_status == '2'">{{
                record.activity_status_txt
              }}</a-tag>
            </template>

            <template v-if="column.key == 'action'">
              <div style="display: flex">
                <a-button type="text" @click="godeatails(record)"
                  >明细</a-button
                >
                <a-button
                  type="text"
                  v-if="record.activity_status !== 2"
                  @click="getQrImage(record)"
                  >下载</a-button
                >
                <a-button
                  v-if="record.activity_status !== 2"
                  type="text"
                  @click="addBurstShop(record)"
                  >编辑</a-button
                >
                <a-button
                  v-if="record.activity_status == '1'"
                  type="text"
                  @click="close_act(record)"
                  >活动失效</a-button
                >
              </div>

              <!-- <a-button type="text">克隆</a-button> -->
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal
      :visible="ModelUpState"
      @cancel="handleClose"
      :footer="null"
      :width="300"
    >
      <template #title>
        <div>
          <span>{{ data_name }} - 活动二维码</span>
        </div>
      </template>
      <div class="mobile">
        <div class="mobile-img">
          <img :src="MobileimgUrl" alt="" />
        </div>
        <a-tooltip placement="top">
          <template #title>
            <span
              >Android 和 iOS 支持分享到抖音发布页功能的最低抖音版本为： <br />
              ​Android：20.8.0 <br />
              ​iOS：21.5.0 ​</span
            >
          </template>
          <div class="mobile-title">
            <div class="one">请使用抖音扫描二维码</div>
            <div class="two">
              <a-button
                type="primary"
                size="small"
                :loading="down_loading"
                style="border-radius: 5px; margin-left: 5px"
                @click="debounceddown_post"
                >下载</a-button
              >
            </div>
          </div>
        </a-tooltip>
      </div>
    </a-modal>

    <BurstShopDetails
      :visible="visible"
      :detailid="detailid"
      @closeFn="closeFn"
    />
  </div>
</template>

<script setup>
import { computed, defineComponent, ref, createVNode } from "vue";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";
import request from "../../../common/utils/request";
import { message, Modal } from "ant-design-vue";
import { debounce } from "lodash";
import BurstShopDetails from "./BurstShopDetails.vue";

const columns = ref([
  {
    title: "活动名称",
    dataIndex: "name",
    key: "name",
    align: "center",
  },
  {
    title: "总播放量",
    dataIndex: "play_count",
    key: "play_count",
    sorter: {
      compare: (a, b) => a.play_count - b.play_count,
    },
    align: "center",
  },
  {
    title: "总转发量",
    dataIndex: "share_count",
    key: "share_count",
    sorter: {
      compare: (a, b) => a.share_count - b.share_count,
    },
    align: "center",
  },
  {
    title: "总评论量",
    dataIndex: "comment_count",
    key: "comment_count",
    sorter: {
      compare: (a, b) => a.comment_count - b.comment_count,
    },
    align: "center",
  },
  {
    title: "总点赞数",
    dataIndex: "digg_count",
    key: "digg_count",
    sorter: {
      compare: (a, b) => a.digg_count - b.digg_count,
    },
    align: "center",
  },
  {
    title: "扫码人数",
    dataIndex: "scan_people_count",
    key: "scan_people_count",
    sorter: {
      compare: (a, b) => a.scan_people_count - b.scan_people_count,
    },
    align: "center",
  },
  {
    title: "扫码次数",
    dataIndex: "scan_times_count",
    key: "scan_times_count",
    sorter: {
      compare: (a, b) => a.scan_times_count - b.scan_times_count,
    },
    align: "center",
  },
  {
    title: "发布人数",
    dataIndex: "release_people_count",
    key: "release_people_count",
    sorter: {
      compare: (a, b) => a.release_people_count - b.release_people_count,
    },
    align: "center",
  },
  {
    title: "发布次数",
    dataIndex: "release_times_count",
    key: "release_times_count",
    sorter: {
      compare: (a, b) => a.release_times_count - b.release_times_count,
    },
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "activity_status",
    key: "activity_status",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "created_at",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    fixed:'right'
  },
]);
const router = useRouter();
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dataSource = ref([]);
const loading = ref(false);

const pagination = computed(() => ({
  total: total.value,
  page: page.value,
  pageSize: pageSize.value,
  // showTotal: (total) => `共${total}条`,
}));
const handleTableChange = (pager, filters, sorter) => {
  console.log("Sorting:", sorter);
  page.value = pager.current;
  pageSize.value = pager.pageSize;

  if (sorter && sorter.columnKey) {
    const sortField = sorter.field;
    const sortOrder = sorter.order === "ascend" ? 1 : -1;

    dataSource.value.sort((a, b) => {
      if (a[sortField] < b[sortField]) return -1 * sortOrder;
      if (a[sortField] > b[sortField]) return 1 * sortOrder;
      return 0;
    });
  } else {
    initData({
      page: page.value,
      pageSize: pageSize.value,
    });
  }
};
const addBurstShop = (item) => {
  if (item) {
    router.push({
      name: "BurstShopDetail",
      query: { id: item.id },
    });
  } else {
    router.push({
      name: "BurstShopDetail",
    });
  }
};

const visible = ref(false);
const detailid = ref("");
const godeatails = (item) => {
  detailid.value = item.id;
  visible.value = true;
  // router.push({
  //   name: "BurstShopDetails",
  //   query: { id: item.id },
  // });
};

const initData = () => {
  let params = {
    page: page.value,
    pageSize: pageSize.value,
  };

  // 函数用于移除 updated_at 字符串最后的冒号及其后面的内容
function formatUpdatedAt(updatedAt) {
  if (updatedAt) {
    let lastColonIndex = updatedAt.lastIndexOf(":");
    if (lastColonIndex !== -1) {
      return updatedAt.slice(0, lastColonIndex);
    }
  }
  return updatedAt;
}
  request
    .get("/work_ai", "/hotStore/activity/list", params)
    .then((res) => {
      dataSource.value = res.result.data.map((item) => ({
        ...item,
        play_count:
          item.stats && item.stats.play_count !== null
            ? item.stats.play_count
            : "0",
        share_count:
          item.stats && item.stats.share_count !== null
            ? item.stats.share_count
            : "0",
        comment_count:
          item.stats && item.stats.comment_count !== null
            ? item.stats.comment_count
            : "0",
        digg_count:
          item.stats && item.stats.digg_count !== null
            ? item.stats.digg_count
            : "0",
        scan_people_count:
          item.stats && item.stats.scan_people_count !== null
            ? item.stats.scan_people_count
            : "0",
        scan_times_count:
          item.stats && item.stats.scan_times_count !== null
            ? item.stats.scan_times_count
            : "0",
        release_people_count:
          item.stats && item.stats.release_people_count !== null
            ? item.stats.release_people_count
            : "0",
        release_times_count:
          item.stats && item.stats.release_times_count !== null
            ? item.stats.release_times_count
            : "0",
        created_at: formatUpdatedAt(item.created_at), 
              end_time: formatUpdatedAt(item.end_time),
      }));
      total.value = res.result.total;
    })
    .catch((err) => {});
};

const ModelUpState = ref(false);
const MobileimgUrl = ref("");
const data_name = ref("");
const getQrImage = async (data) => {
  let params = {
    id: data.id,
  };
  const res = await request.get("/work_ai", "/user/activity/qrcode", params);
  let qrcodeParams = {
    qrCode: res.result,
  };

  const res1 = await request.get("/public", "/qrcode", qrcodeParams);
  MobileimgUrl.value = res1.url;
  ModelUpState.value = true;
  data_name.value = data.name;
};

const down_loading = ref(false);

const down_post = async () => {
  if (!down_loading.value) {
    try {
      if (!MobileimgUrl.value) {
        message.error("无效的图片链接");
        return;
      }
      down_loading.value = true;
      const response = await fetch(MobileimgUrl.value);
      if (!response.ok) {
        throw new Error("网络响应失败");
      }
      const blob = await response.blob();
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = "poster.jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      message.success("下载成功！");
      down_loading.value = false;
    } catch (error) {
      message.error("下载失败，请稍后再试。");
      down_loading.value = false;
    }
  }
};

const debounceddown_post = debounce(down_post, 1000, {
  leading: true,
  trailing: false,
});

const handleClose = () => {
  ModelUpState.value = false;
};

const close_act = (item) => {
  Modal.confirm({
    title: `活动尚未到期，确定提前结束吗？`,
    icon: createVNode(ExclamationCircleOutlined),
    cancelText: "取消",
    okText: "确定",
    onOk() {
      request
        .put("/work_ai", "/user/activity/over", {
          id: item.id,
        })
        .then((res) => {
          message.success("操作成功!");
          initData();
        });
    },
  });
};

const closeFn = () => {
  visible.value = false;
};

initData();
</script>

<style lang="less">
.popover_con {
  .ss-tooltip-inner {
    min-width: 560px !important;
  }
}

.popover_cons {
  .ss-tooltip-inner {
    min-width: 200px !important;
  }
}
</style>
<style lang="less" scoped>
.smart-clip-header {
  padding: 30px;
  border-radius: 12px;
  // height: 180px;
  min-width: 1140px;
  // margin-top: 20px;
  background: linear-gradient(220deg, #f3f7ff, rgba(159, 191, 255, 0.4));
  display: flex;
  flex-direction: column;
  margin-bottom: 24px;

  .smart-clip-header-title_top {
    font-size: 24px;
    color: #0c0d0e;
    line-height: 1.5;
  }

  .smart-clip-header-desc {
    font-size: 14px;
    color: #737a87;
    margin-top: 5px;
    line-height: 1.5;
  }

  .smart-clip-header-btngroup {
    margin-top: 15px;
  }
}

.content_card {
  width: 100%;
  background-color: #fff;
  padding: 20px;
  .top_btn {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }
  .add_btn {
    border-radius: 5px;
  }
}

.name_content {
  display: flex;
  .left {
    width: 100px;
    height: 150px;
    background-color: #999;
    position: relative;
    .corver_img {
      width: 100%;
      height: 100%;
    }

    .new_content_code {
      position: absolute;
      width: 40px;
      height: 40px;
      bottom: 10px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
  .right {
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    text-align: left;
    .right_two {
      text-align: left;
      // color: #000;
    }

    .right_one {
      max-width: 130px;
      overflow: hidden;
      word-wrap: break-word;
      word-break: break-all;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      text-overflow: ellipsis;
    }
  }
}

.mobile-img {
  display: flex;
  justify-content: center;
  align-items: center;
  // padding: 0 20px;

  img {
    width: 100%;
  }
}

.mobile-title {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
